<?php
	defined( '_JEXEC' ) or die( 'Restricted access' );
	jimport( 'joomla.application.component.model' );
	require_once(JPATH_COMPONENT.DS.'libraries'.DS.'core.php' );
	
	class ModelHizkimizkiHiztegi extends JModel
	{
		var $_hiztegi =null;
		
		function __construct()
		{
			parent::__construct();
		}
		
		private function parseHiztegi($origWords,$destWords){
			$langOri=new Language($origWords[0]->idLanguage);
			$langDest=new Language($destWords[0]->idLanguage);
			$this->_hiztegi=new Hiztegi($langOri, $langDest);
			
			$numTranslations=count($origWords);
			$wordsOri=array();
			$wordsDest=array();
			for($i=0;$i<$numTranslations;$i++){
				$wordOri=new Word($origWords[$i]->id);
				$wordOri->setLanguage($langOri);
				$wordOri->setWord($origWords[$i]->word);
				$wordsOri[]=$wordOri;
				$wordDest=new Word($destWords[$i]->id);
				$wordDest->setLanguage($langDest);
				$wordDest->setWord($destWords[$i]->word);
				$wordsDest[]=$wordDest;
			}
			$this->_hiztegi->setWordsOri($wordsOri);
			$this->_hiztegi->setWordsDest($wordsDest);
		}
		
		private function getWords($lang){
			$db =& JFactory::getDBO();
			
			$query = "SELECT * 
						FROM `#__hizkimizki_words` 
						WHERE `idLanguage` = '$lang' 
						ORDER BY `wordNum";
			$db->setQuery( $query );
			$words=$db->loadObjectList();
			
			return $words;
		}

		private function getLang($lang){
			$db =& JFactory::getDBO();
			
			$query = "SELECT * 
						FROM `#__hizkimizki_languages` 
						WHERE `id` = '$lang'";
			$db->setQuery( $query );
			$lang=$db->loadObject();
			
			return $lang;
		}
		
		public function createHiztegi(){
			
			$langOri=JRequest::getVar('langOri',0);
			$langOriName=JRequest::getVar('langOriName',$langOri);
			$langDest=JRequest::getVar('langDest',0);
			$langDestName=JRequest::getVar('langDestName',$langDest);
			
			$origWords=$this->getWords($langOri);
			$destWords=$this->getWords($langDest);
			$oriLang=$this->getLang($langOri);
			$destLang=$this->getLang($langDest);

			$this->parseHiztegi($origWords,$destWords);
			$this->_hiztegi->_langOri->setName($langOriName);
			$this->_hiztegi->_langDest->setName($langDestName);
			$this->_hiztegi->_langOri->setAuthor($oriLang->authorName);
			$this->_hiztegi->_langDest->setAuthor($destLang->authorName);
			return $this->_hiztegi;
		}
		
		public function getHiztegi(){
			return $this->_hiztegi;
		}
	}
	
?>